An interface is a blueprint for a class that defines a set of abstract methods. Interfaces are implemented by classes using the implements keyword.
// Defining an interface
interface Vehicle {
void start(); // Abstract method (no body)
void stop(); // Abstract method
}
// Implementing the interface
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting");
}
public void stop() {
System.out.println("Car has stopped");
}
}
class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.start();
myCar.stop();
}
}
A package is a collection of related classes and interfaces. It helps in organizing the code and avoids class name conflicts.
// Creating a package
package mypackage;
public class Example {
public void display() {
System.out.println("This is a package example");
}
}
To use a class from another package, use the import keyword.
import mypackage.Example; // Importing specific class
class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.display();
}
}
java.util
, java.io
.import packageName.*;